/*

log2mongo :: Logs messages to MongoDB
__________________________________________

Copyright (c) 2011 Gaurav Kumar, Pivotal Security LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
#include <stdlib.h>
#include <string>
#include <sstream>
#include <list>
#include <iostream>
#include <pthread.h>
#include <signal.h>
#include <sys/select.h>
#include "client/dbclient.h"
using namespace mongo;



// the muticies, protectors of the shared resources
pthread_mutex_t coutLock;
pthread_mutex_t inQueueLock;
pthread_mutex_t outQueueLock;
// the shared data
std::list< std::string > inQueue;
std::list< std::string > outQueue;

struct thread_detail { // information to pass to worker threads
 unsigned long num;
};

extern "C" {
    void *workerThread(void *threadarg);
}

void *workerThread(void *threadarg)
{
   using namespace std;
   struct timeval timeout;
   DBClientConnection c;
   c.connect("192.168.1.127");
   struct thread_detail *my_data;
   my_data = (thread_detail *) threadarg;
   int taskid = my_data->num;
   std::stringstream ss;
   ss<<taskid;
   std::string taskString(ss.str());


  for(;;) // keep on working and never die
    {

      pthread_mutex_lock( &inQueueLock );
      std::string workOnMe;
      if (inQueue.size()==0)
            {

                 cout<<taskString<<":I am hugry! so going to add something to the queue"<<endl;

                auto_ptr<DBClientCursor> cursor = c.query("logs.authLog", QUERY("ctr"<<1));
        if(cursor->more()){
                cout << cursor->next().toString() << endl;
                 inQueue.push_back(cursor->next().toString() );
                } else {
                cout<<"No docs found :("<<endl;

                }

                }
                cout<<"I am thread # "<<taskString<<" and Queue size is "<<inQueue.size()<<endl;
                cout<<"I am thread # "<<taskString<<" and front of queue  is "<<inQueue.front()<<endl;

         inQueue.pop_front();

      pthread_mutex_unlock( &inQueueLock );


      timeout.tv_sec = 1;  timeout.tv_usec = 0; // 0.1 second delay
      select( 0, NULL, NULL, NULL, & timeout );
         // cout<<workOnMe<<endl;

    } // never die for loop

   pthread_exit(NULL);
}


int main (int argc, char *argv[])
{


using namespace std;

  unsigned long comp_START=0;
  // set-up the mutexes
  pthread_mutex_init( &coutLock, NULL );
  pthread_mutex_init( &inQueueLock, NULL );
  pthread_mutex_init( &outQueueLock, NULL );

  if (argc != 2) { std::cout<<"usage: ./binary #of threads"; exit(1); }
  unsigned long NUM_THREADS(atoi( argv[1] ));
  unsigned long comp_TODO(10);
  std::cout<<"Program will have "<<NUM_THREADS<<" threads, working on "<<comp_TODO<<" things \n";


  // start the worker threads
  std::list< pthread_t* > threadIdList; // just the thread ids
  std::list< thread_detail > thread_table; // for keeping track of information on the various threads we'll create
  for (unsigned long i=0; i<NUM_THREADS; i++) // start the threads
   {
    pthread_t *tId( new pthread_t );   threadIdList.push_back(tId);
    thread_detail Y; Y.num=i; thread_table.push_back(Y);
    int rc( pthread_create( tId, NULL, workerThread, (void *)(&(thread_table.back() )) ) );
    if (rc) { std::cout<<"ERROR; return code from pthread_create() "<<comp_START<<"\n"; std::cout.flush();
              exit(-1); }
   }
  // now we wait for the threads to terminate, perhaps updating the screen with info as we go.
  std::string stringOut;


   // call join to kill all worker threads
   std::list< pthread_t* >::iterator i(threadIdList.begin());
  while (i!=threadIdList.end())
   {
    if (pthread_join( *(*i), NULL)!=0) { std::cout<<"Thread join error!\n"; exit(1); }
    delete (*i);
    threadIdList.erase(i++);
   }
  std::cout<<"\n";

    pthread_mutex_destroy(&coutLock);
    pthread_mutex_destroy(&inQueueLock);
    pthread_mutex_destroy(&outQueueLock);
    // pthread_exit(NULL);
}
